<template>
  <div class="upload-container">
    <div class="upload-content">
      <el-upload ref="upload"
                 :action="uploadUrl"
                 :headers="headers"
                 :on-error="handleError"
                 :multiple="false"
                 :before-upload="beforeUpload"
                 :limit="limit"
                 :on-exceed="handleExceed"
                 :file-list="fileList"
                 :before-remove="handleRemove">
        <el-button size="small">选择上传的文档</el-button>
      </el-upload>
      <div class="upload-options"
           v-if="percent&&percent!=100&&!done">
        <el-link type="info"
                 @click="PauseUpload"
                 class="upload-icons"
                 :underline="false"
                 :icon="!Pause?'el-icon-document-pause':'el-icon-document-play'"></el-link>
        <el-link type="info"
                 class="upload-icons"
                 :underline="false"
                 @click="RefreshUpload"
                 icon="el-icon-refresh"></el-link>
        <el-link icon="el-icon-circle-close"
                 class="upload-icons"
                 @click="CancelUpload"
                 :underline="false"></el-link>
      </div>

    </div>

    <el-progress v-if="percent&&percent!=100&&!done"
                 :percentage="percent"></el-progress>
    <el-button v-if="fileList.length > 0 &&!done"
               slot="trigger"
               size="small"
               type="primary"
               :loading="loading"
               @click="startUpload">

      开始上传

    </el-button>

  </div>
</template>

<script>
import md5 from "md5"
import axios from "axios"
import { SHA512 } from 'crypto-js';
import { getAccessToken } from "@/utils/auth"
import { calculateSHA512 } from '@/utils/encrypt';
import { UploadBigFile } from "@/api/modules/upload"
import { cancelUpload, restartUpload, multipleAbort, uploadBigFileToCos, deleteUploadFile } from '@/api/cos';

export default {
  props: {
    document_url: {
      type: String,
    }
  },
  data () {
    return {
      uploadUrl: '/api/v1/upload/bigFileUpload',
      headers: {
        'Content-Type': 'multipart/form-data',
        'authorization': getAccessToken()
      },
      percent: 0,
      fileList: [],
      documentUrl: "",
      // 上传完成判断
      done: false,
      // 暂停标志位
      Pause: false,
      currentChunk: 0,
      total: 0,
      loading: false,
      end_prefix: "",
      limit: 1,
      currentFile: null
    };
  },
  computed: {
    chunkSize () {
      return 1024 * 1024
    },
    timemd5 () {
      return md5(new Date().toString())
    }
  },
  watch: {
    document_url: {
      immediate: true,
      handler (val) {
        this.fileList = []
        if (val) {
          this.documentUrl = val
          this.fileList.push({
            name: `edited-image${val}`,
            url: val
          })
          this.$store.commit("upload/SETDOCUMENTURL", this.documentUrl)

        }
      }
    }
  },
  methods: {
    onProgress (progress) {
      console.log("进度", progress)
      // 更新上传进度
      this.percent = progress.percent * 100

    },
    handleExceed (files, fileList) {
      console.log("超出限制")
      // 文件数量超过限制的回调函数
      this.$message.warning(`只能上传 ${this.limit} 个文件`);
    },
    // 开始上传
    async startUpload () {

      const file = this.$refs.upload.uploadFiles[0];
      this.currentFile = file
      // 格式校验
      // 格式校验
      const allowedExtensions = ['.pptx', '.pdf', '.doc', '.docx', '.txt', '.xlsx', '.xls'];
      const allowedMimeTypes = [
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'text/plain',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ];

      const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
      const fileMimeType = file.type;

      // 检查文件扩展名
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 PPT、PDF、DOC、DOCX、TXT 或 Excel 格式的文档');
        this.fileList = [];
        return;
      }
      this.done = false
      this.loading = true
      // 检查文件 MIME 类型
      if (!allowedMimeTypes.includes(fileMimeType)) {
        this.$message.error('只能上传 PPT、PDF、DOC、DOCX、TXT 或 Excel 格式的文档');
        this.fileList = [];
        return;
      }
      // 如果文件存在
      if (file) {
        // cos存储
        uploadBigFileToCos(file, file.name, this.onProgress)
          .then((completeData) => {
            // 上传完成后的处理逻辑
            this.done = true;
            this.loading = false;
            this.percent = 100;
            this.documentUrl = 'http://' + completeData.Location

            this.$message.success("上传成功")
            // 监听取消发布并删除事件
            this.$bus.$on("RemoveUploadFile", this.RemoveUploadFile)

            // 存储url
            this.$store.commit("upload/SETDOCUMENTURL", this.documentUrl)

          })
          .catch((error) => {
            console.log(error)
          });
        // 本地存储
        // const { chunkSize, timemd5 } = this
        // const totalChunks = Math.ceil(file.size / this.chunkSize)
        // console.log('total', totalChunks)
        // if (totalChunks == 0) return this.$message.error('无法上传空文件')
        // // 检查文件是否存在
        // const fileReader = new FileReader()
        // fileReader.onload = async () => {
        //   const arrayBuffer = fileReader.result;
        //   const uint8Array = new Uint8Array(arrayBuffer);
        //   // 格式转换
        //   const fileBlob = new Blob([arrayBuffer], { type: file.type });
        //   // 生成hash值
        //   const file_hash = await calculateSHA512(fileBlob);
        //   const datas = this.$qs.stringify({ file_hash })
        //   try {
        //     // 检查是否存在相同文件
        //     const res = await this.$API.upload.CheckExist(datas)
        //     if (res && res.status == 200) {
        //       this.done = true
        //       this.percent = 100
        //       this.documentUrl = res.data.url
        //       this.loading = false
        //       console.log('documenturl', this.documentUrl)
        //       this.$store.commit("upload/SETDOCUMENTURL", this.documentUrl)
        //       // this.fileList = []
        //       this.$message.success("上传成功")
        //       return
        //     }
        //   } catch (error) {
        //     this.$message.error("文件检查请求失败")
        //     return;
        //   }
        //   // 判断是否上传完了
        //   while (this.currentChunk < totalChunks && !this.done && !this.Pause) {
        //     const start = this.currentChunk * chunkSize;
        //     const end = Math.min(file.size, start + chunkSize);
        //     const chunk = file.slice(start, end);
        //     // 构建表单数据
        //     const formData = new FormData();
        //     this.total = file.size
        //     this.end_prefix = file.name.split(".").pop()
        //     formData.append('file', chunk);
        //     formData.append('start', start);
        //     formData.append('end', end);
        //     formData.append('total', this.total);
        //     formData.append('timemd5', timemd5);
        //     formData.append('end_prefix', this.end_prefix);

        //     // 发送分片请求
        //     try {
        //       await UploadBigFile(formData, {
        //         headers: {
        //           'Content-Type': 'multipart/form-data',
        //           'Authorization': getAccessToken()
        //         },
        //         onUploadProgress: progressEvent => {
        //           // 监听上传进度
        //           this.percent = Math.ceil((this.currentChunk / totalChunks) * 100);
        //           console.log('上传进度:', this.percent);
        //         }
        //       }).then(res => {
        //         console.log(res)
        //         // 如果上传完成
        //         if (res.data.data.done && this.currentChunk === totalChunks - 1) {
        //           this.done = true
        //           this.loading = false
        //           this.percent = 100
        //           this.documentUrl = res.data.data.url
        //           // 存储到vuex中
        //           this.$store.commit("upload/SETDOCUMENTURL", this.documentUrl)
        //           this.fileList = []
        //           this.$message.success("上传成功")
        //           this.$bus.$on("RemoveUploadFile", this.RemoveUploadFile)
        //         }
        //       });

        //       this.currentChunk++;
        //     } catch (error) {
        //       this.$message.error("上传失败")
        //       this.done = false
        //       this.Pause = true
        //       console.error('分片上传失败:', error);
        //       return;
        //     }
        //   }
        // }
        // fileReader.readAsArrayBuffer(file);


      } else {
        console.warn('未选择文件');
      }
    },
    // 中断上传
    async InterruptUpload () {
      this.Pause = true
      const { total, end_prefix, timemd5 } = this
      let datas = new FormData()
      datas.append("total", total)
      datas.append("timemd5", timemd5)
      datas.append("end_prefix", end_prefix)
      try {
        const res = await this.$API.document.InterruptUploaddocument(datas)
        if (res.status == 200) {
          this.currentChunk = 0
          this.percent = 0
        }
      } catch (error) {
        this.$message.error("中断失败")
      }
    },
    // 取消上传
    async CancelUpload () {
      // cos中断上传
      await cancelUpload(this.currentTaskId)
      this.fileList = []
      this.done = true
      this.loading = false
      this.percent = 0
      this.$message.success("取消成功")
      // 本地中断上传
      // this.InterruptUpload().then(() => {
      //   // 清空列表
      //   this.fileList = []
      //   this.Pause = false
      // })

    },
    // 重新上传
    RefreshUpload () {
      // cos重新上传
      cancelUpload()
      this.loading = false
      this.percent = 0;
      this.done = true;
      this.startUpload()
      // 中断后重新开始上传
      // this.InterruptUpload().then(() => {
      //   this.Pause = false
      //   this.done = false
      //   this.currentChunk = 0
      //   this.startUpload()
      // })

    },
    // 暂停上传功能
    async PauseUpload () {
      // cos暂停
      this.Pause = !this.Pause
      // cos中断上传

      if (!this.Pause) {
        await restartUpload(this.currentTaskId)
      } else {
        await multipleAbort(this.currentTaskId)
      }
      // 本地暂停
      // this.Pause = !this.Pause
      // if (!this.Pause) {
      //   this.startUpload()
      // }
    },
    handleError (error, file) {
      // 上传失败的回调函数
      console.error('上传失败', error, file);
    },
    beforeUpload (file) {
      this.fileList.push(file)
      this.currentChunk = 0
      this.done = false
      // 阻止自动上传
      return false;
    },
    async handleRemove (file) {

      console.log('remove', file)
      if (file.status == 'success') {

        // 如果存在url,就删除该文件
        if (this.documentUrl) {
          // cos存储删除
          const formData = new FormData()
          formData.append('url', this.documentUrl)
          // 检查是否关联
          const res = await this.$API.upload.DetectCosRemove(formData)
          if (res.status == 200) {
            // 删除cos存储文件
            const response = await deleteUploadFile('file/' + file.name)
            if (res.status == 200 || res.status == 204) {
              this.fileList = []
              this.documentUrl = ""
            } else {
              return this.$message.error(res.msg)
            }
          } else if (res.status == 422) {
            this.fileList = []
            this.documentUrl = ""
          }
          // 本地存储删除
          // this.RemoveUploadFile(this.documentUrl)
        }

      }
      // this.fileList = []
    },
    // 删除多余上传的文件
    async RemoveUploadFile (url) {
      console.log(url)
      if (!url) return
      // cos删除
      const formData = new FormData()
      formData.append('url', url)
      // 检查是否关联
      const res = await this.$API.upload.DetectCosRemove(formData)
      if (res.status == 200) {
        // 删除cos存储文件
        const response = await deleteUploadFile('file/' + this.currentFile.name)
        if (res.status == 200 || res.status == 204) {
          this.fileList = []
          this.documentUrl = ""
        } else {
          return this.$message.error(res.msg)
        }
      } else if (res.status == 422) {
        this.fileList = []
        this.documentUrl = ""
      }
      // 本地删除
      // const datas = new FormData()
      // datas.append("url", url)
      // const res = await this.$API.upload.DeleteAlreadyUploadFile(datas)
      // if (res.status == 200) {
      //   this.documentUrl = ""
      //   this.fileList = []

      // }
    }
  }
}
</script>
<style scoped>
.upload-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.upload-content {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.upload-options {
  margin-right: 20px;
  margin-top: 20px;
}
.upload-icons {
  margin-left: 12px;
  font-size: 18px;
}
</style>